class WidgetsController < ApplicationController
  before_filter :require_admin
  before_filter :find_or_initialize_friend_widget, :except => [:index, :create]
  # GET /widgets
  # GET /widgets.xml
  def index
    @widgets = Widget.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @widgets }
    end
  end

  # GET /widgets/1
  # GET /widgets/1.xml
  def show
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @widget }
    end
  end

  # GET /widgets/new
  # GET /widgets/new.xml
  def new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @widget }
    end
  end

  # GET /widgets/1/edit
  def edit
  end

  # POST /widgets
  # POST /widgets.xml
  def create
    @widget = Widget.new(params[:widget])

    respond_to do |format|
      if @widget.save
        format.html { redirect_to(root_url, :notice => '小工具创建成功.') }
        format.xml  { render :xml => @widget, :status => :created, :location => @widget }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @widget.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /widgets/1
  # PUT /widgets/1.xml
  def update
    respond_to do |format|
      if @widget.update_attributes(params[:widget])
        format.html { redirect_to(root_url, :notice => '小工具更新成功.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @widget.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /widgets/1
  # DELETE /widgets/1.xml
  def destroy
    @widget.destroy

    respond_to do |format|
      format.html { redirect_to(root_url) }
      format.xml  { head :ok }
    end
  end

  private
  def find_or_initialize_friend_widget
    @widget = params[:id] ? Widget.find(params[:id]) : Widget.new
  end
  # => 清除右侧小工具的缓存
  def expire_fragment_cache
    expire_fragment(RecordSweeper::PATH.merge(:action_suffix => 'show_widgets'))
  end

end
